<template>
  <div>
    <el-form :model="form" label-width="auto" inline :rules="rules" ref="ruleFormRef">

      <el-form-item label="选择仓库:" prop="inventoryWarehouseDicList">
        <el-select v-model="form.inventoryWarehouseDicList" value-key="key" clearable>
          <el-option :label="item.value" :value="item" v-for="(item) in   store.WarehouseTypeListss  "
            @click="houseChange(item.inventoryDicList)" :key="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="盘货货区:" prop="inventoryDicList">
        <el-select v-model="form.inventoryDicList" value-key="key" clearable>
          <el-option label="全部" :value="0" />
          <el-option :label="item.value" :value="item" v-for="(item) in   indexs" :key="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="分配状态:" prop="region">
        <el-select v-model="form.region" clearable>
          <el-option label="全部" :value="0" />
          <el-option label="未分配" :value="1" />
          <el-option label="已分配" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间:">
        <el-date-picker v-model="form.times" type="datetimerange" start-placeholder="开始时间" value-format="x"
          end-placeholder="结束时间" time-format="A hh:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">搜索</el-button>
        <el-button type="primary" @click="setNewOrder">生成新的盘货单</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="仓库" width="180">
        <template #default="scope">{{ scope.row.warehouseName }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="盘货货区" width="180">
        <template #default="scope">{{ scope.row.warehouseAreaName }}</template>
      </el-table-column>
      <el-table-column label="操作人" width="180">
        <template #default="scope"><span class="headclass" @click="open(scope.row)">去分配</span></template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="delectOrder(scope.row)">
            取消
          </el-button>
          <el-button link type="primary" size="small" @click.prevent="PrintInventory(scope.row)">
            打印盘货单
          </el-button>
          <el-button link type="primary" size="small" v-if="scope.row.isPrint" @click.prevent="lookDetails(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 新增 -->
  <el-dialog v-model="dialogVisible" width="500">
    <span>
      <el-checkbox-group v-model="checkList">
        <el-checkbox :label='item.key' :value="item.key" v-for="item in kuqu" :key="item.key">{{
      item.value
    }}</el-checkbox>
      </el-checkbox-group>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setNewConfirm">
          确认生成
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 分配 -->
  <el-dialog v-model="dialogVisibleAllocation" width="580">
    <span>
      <div style="margin-bottom: 40px;">待盘货货区：{{ names }}</div>
      <el-form :model="formAllocation" inline>
        <el-form-item label="操作人:">
          <el-select v-model="formAllocation.roleId" clearable>
            <el-option :label="item.value" :value="item.key" v-for="(item, index) in  openList  " :key="index"
              @click="AllocationChange(item.inventoryUserDicList)" />
          </el-select>
          <el-select v-model="formAllocation.userId" clearable>
            <el-option :label="items.value" :value="items.key" v-for="(items, indexs) in AllocationChangeTables"
              :key="indexs" />
          </el-select>
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleAllocation = false">取消</el-button>
        <el-button type="primary" @click="AllocationConfirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 查看详情 -->
  <div>
    <el-dialog v-model="dialogVisibleDetails" width="700">
      <span>
        <el-table :data="dialogVisibleDetailsTable" style="width: 100%">
          <el-table-column width="120">
            <template #default="scope">{{ scope.row.skuInfo }}</template>
          </el-table-column>
          <el-table-column width="210">
            <template #default="scope">库位号：{{ scope.row.warehouseLocationName }}</template>
          </el-table-column>
          <el-table-column width="190">
            <template #default="scope">系统库存数：{{ scope.row.stockNum }}</template>
          </el-table-column>
        </el-table>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive, onBeforeUnmount } from 'vue'
import { inventoryList, inventorycreate, inventoryDelect, listSubWarehouseLocation, inventoryCreateSubWarehouseLocation, creatInventoryDic, assignmentDic, inventoryassignment } from '@/api/index'
import { useAlertsStore } from '@/store/index'
import { ElMessage } from 'element-plus'
const store = useAlertsStore()
// do not use same name with ref
const form = ref({
  pageSize: 10,
  pageNum: 1,
  region: 0,
  times: '',
  inventoryWarehouseDicList: '',
  inventoryDicList: 0
})
const ruleFormRef = ref()
const rules = reactive({
  inventoryWarehouseDicList: [
    { required: true, message: '必填', trigger: 'change' }
  ],
  inventoryDicList: [
    {
      required: true,
      message: '必选',
      trigger: 'change'
    }
  ],
  region: [
    {
      required: true,
      message: '必选',
      trigger: 'change'
    }
  ]
})
const tableData = ref([])
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      getList()
    } else {
      console.log('error submit!', fields)
    }
  })
}

onBeforeMount(() => {
  doConnect()
  store.searchInventoryDicApi()
  // store.getWarehouseAreaDownListApi(-1)
  getList(0)
})

const getList = () => {
  console.log(form.value.times)
  inventoryList({
    createTimeStart: form.value.times ? form.value.times[0] : '',
    createTimeEnd: form.value.times ? form.value.times[1] : '',
    warehouseId: form.value.inventoryWarehouseDicList ? form.value.inventoryWarehouseDicList.key : '',
    warehouseAreaId: form.value.inventoryDicList ? form.value.inventoryDicList.key : 0,
    assignmentStatus: form.value.region ? form.value.region : '0',
    confirmStatus: 1,
    inventoryType: 0,
    pageSize: form.value.pageSize,
    pageNum: form.value.pageNum
  }).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 生成盘活单
const dialogVisible = ref(false)
const kuqu = ref([])
const checkList = ref([])
const setNewOrder = () => {
  if (form.value.inventoryWarehouseDicList) {
    console.log(form.value.inventoryWarehouseDicList.key)
    creatInventoryDic({ warehouseId: form.value.inventoryWarehouseDicList.key }).then(res => {
      dialogVisible.value = true
      const { data: { data } } = res
      kuqu.value = data.inventoryDicList
    })
  } else {
    ElMessage.error('先选择仓库')
  }
}
const setNewConfirm = () => {
  inventorycreate({ warehouseId: form.value.inventoryWarehouseDicList.key, integers: checkList.value }).then(res => {
    dialogVisible.value = false
    ElMessage.success('操作成功')
    getList()
  })
}
// 取消
const delectOrder = (val) => {
  inventoryDelect({ inventoryId: val.id }).then(res => {
    ElMessage.success('操作成功')
    getList()
  })
}
// cangku
const indexs = ref([])
const houseChange = (index) => {
  indexs.value = index
}
// 打印盘活
const orLook = ref(false)
const PrintInventory = (row) => {
  orLook.value = true
  inventoryCreateSubWarehouseLocation(row.id).then(res => {
    const { data: { data } } = res
    // ElMessage.success('操作成功')
    if (localStorage.getItem('PrinterSetListPH')) {
      const lists = JSON.parse(localStorage.getItem('PrinterSetListPH'))
      console.log(lists[0].PrinterList)
      console.log(data.pdaCode)
      console.log(data.inboundBatchesCode)
      const val = {
        cmd: 'print',
        requestID: '123458976',
        version: '1.0',
        task: {
          taskID: (new Date().getTime() + ''),
          preview: false,
          printer: lists[0].PrinterList,
          notifyMode: 'allInOne',
          previewType: 'pdf',
          documents: [{
            documentID: '0123456789',
            contents: [{
              data: {
                width: '210',
                height: '297',
                padding: '2',
                fontSize: '8',
                left: '2',
                skuInfo: data.listSubWarehouseLocation,
                code: data.pdaCode,
                goodsArea: data.warehouseArea.name,
                barcodeHeight: '33'
              },
              templateURL: 'http://yitaoweb.sc.kuaidi600.com/moban/A4Ph.xml'
            }]
          }]
        }
      }
      store.socket.send(JSON.stringify(val))
      getList()
    } else {
      ElMessage.success('先设置打印机')
    }
  })
}
// 分配
const dialogVisibleAllocation = ref(false)
const formAllocation = ref({})
const names = ref('')
const inventoryIdsa = ref('')
const openList = ref({})
const open = (row) => {
  dialogVisibleAllocation.value = true
  inventoryIdsa.value = row.id
  names.value = row.warehouseAreaName
  assignmentDic(row.id).then(res => {
    const { data: { data } } = res
    openList.value = data.inventoryRoleDics
    console.log(openList.value)
  })
}
const AllocationConfirm = () => {
  // 确认
  inventoryassignment({ inventoryId: inventoryIdsa.value, inventoryAssignmentParam: formAllocation.value }).then(res => {
    dialogVisibleAllocation.value = false
    ElMessage.success('操作成功')
    getList()
  })
}
const AllocationChangeTables = ref([])
const AllocationChange = (item) => {
  AllocationChangeTables.value = item
  formAllocation.value.userId = ''
}
// 查看详情
const dialogVisibleDetailsTable = ref([])
const lookDetails = (row) => {
  dialogVisibleDetails.value = true
  listSubWarehouseLocation(row.id).then(res => {
    console.log(res)
    console.log('res')
    const { data: { data } } = res
    dialogVisibleDetailsTable.value = data
  })
  console.log('查看详情')
}
const dialogVisibleDetails = ref(false)
// 销毁
onBeforeUnmount(() => {
  console.log('销毁')
  store.destroyed()
})
const doConnect = () => {
  console.log('d打开了不')
  store.socket = new WebSocket('ws://localhost:13528')
  // 打开Socket
  store.socket.onopen = function (event) {
    // 监听消息
    store.socket.onmessage = function (event) {
      // localStorage.setItem('printerproperties', event.data)
    }
    // 监听Socket的关闭
    store.socket.onclose = function (event) {
      // console.log('Client notified socket has closed', event)
    }
  }
}
</script>

<style lang='less' scoped></style>
